import { useMemo, useState } from 'react';
import { Space, Input, Button, Typography, Card, Tag, Empty, Alert } from 'antd';
import { useLocation } from 'react-router-dom';

function validateStackWithTrace(
  values: number[]
): Array<{ index: number; value: number; isTop: boolean; pass: boolean; reason?: string }> {
  return values.map((v, i, arr) => ({
    index: i,
    value: v,
    isTop: i === arr.length - 1,
    pass: Number.isFinite(v),
    reason: Number.isFinite(v) ? undefined : '非有限数字',
  }));
}

export default function StackVisualizer() {
  const [input, setInput] = useState('1,2,3');
  const [opValue, setOpValue] = useState('4');
  const location = useLocation();
  const isOverviewMode = location.pathname === '/stack';
  const isValidateMode = location.pathname.startsWith('/stack/validate');

  const values = useMemo(
    () =>
      input
        .split(/[\s,]+/)
        .filter(Boolean)
        .map(Number),
    [input]
  );
  const trace = useMemo(() => validateStackWithTrace(values), [values]);
  const hasInvalid = useMemo(() => trace.some((t) => !t.pass), [trace]);

  const push = () =>
    setInput((prev) => [...prev.split(/[\s,]+/).filter(Boolean), opValue].join(','));
  const pop = () =>
    setInput((prev) =>
      prev
        .split(/[\s,]+/)
        .filter(Boolean)
        .slice(0, -1)
        .join(',')
    );

  return (
    <Space direction="vertical" size="middle" style={{ width: '100%' }}>
      <Typography.Title level={2}>栈（Stack）可视化</Typography.Title>

      {isOverviewMode && (
        <Alert
          message="栈概述：定义与验证"
          description={
            <Typography.Paragraph style={{ marginBottom: 0 }}>
              定义：后进先出（LIFO）的线性结构，<Typography.Text strong>栈顶</Typography.Text>
              为可被移除或追加的末尾位置。
              <br />
              验证：基础检查为“节点值是否为有限数字”，同时标注栈顶元素位置以辅助理解。
            </Typography.Paragraph>
          }
          type="info"
          showIcon
        />
      )}

      {isValidateMode && (
        <Alert
          message="验证过程（值检查与栈顶标注）"
          description={
            <Typography.Paragraph style={{ marginBottom: 0 }}>
              逐元素检查是否为有效数字，并标注栈顶元素位置（最后一个）。
            </Typography.Paragraph>
          }
          type={hasInvalid ? 'warning' : 'success'}
          showIcon
        />
      )}

      <Space>
        <Input
          allowClear
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="例如: 1,2,3"
          style={{ width: 320 }}
        />
        <Input
          allowClear
          value={opValue}
          onChange={(e) => setOpValue(e.target.value)}
          placeholder="操作值，例如: 4"
          style={{ width: 160 }}
        />
      </Space>
      <Space>
        <Button onClick={push}>入栈（push）</Button>
        <Button danger onClick={pop}>
          出栈（pop）
        </Button>
      </Space>

      {isValidateMode && (
        <Card title="验证步骤（索引与栈顶）" size="small">
          {values.length === 0 ? (
            <Empty description="空栈" />
          ) : (
            <div style={{ display: 'grid', rowGap: 8 }}>
              {trace.map((t) => (
                <div key={t.index} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <Tag color={t.pass ? 'green' : 'red'}>{t.pass ? '✓' : '✗'}</Tag>
                  <Typography.Text>
                    索引 <Typography.Text code>{t.index}</Typography.Text>，值{' '}
                    <Typography.Text code>{t.value}</Typography.Text>
                    {t.isTop && (
                      <Typography.Text style={{ marginLeft: 8 }} type="secondary">
                        （栈顶）
                      </Typography.Text>
                    )}
                  </Typography.Text>
                  {!t.pass && t.reason && (
                    <Tag color="red" style={{ marginLeft: 8 }}>
                      {t.reason}
                    </Tag>
                  )}
                </div>
              ))}
            </div>
          )}
        </Card>
      )}

      <Card title="栈顶在右侧" size="small">
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          {values.length === 0 ? (
            <Empty description="空栈" />
          ) : (
            values.map((v, i) => (
              <Tag
                key={`${v}-${i}`}
                color={i === values.length - 1 ? 'gold' : 'blue'}
                style={{ padding: '4px 10px' }}
              >
                {v}
              </Tag>
            ))
          )}
        </div>
      </Card>

      <Typography.Text type="secondary">
        提示：右侧为栈顶，push 追加到末尾，pop 移除末尾。
      </Typography.Text>
    </Space>
  );
}
